package com.appkudos.view;

import java.text.DateFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnMultiChoiceClickListener;
import android.os.Bundle;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SimpleAdapter.ViewBinder;
import android.widget.TextView;
import android.widget.Toast;

import com.appkudos.controller.GroupController;
import com.appkudos.controller.UserController;
import com.appkudos.model.App;
import com.appkudos.model.Group;
import com.appkudos.model.Recommendation;
import com.appkudos.model.User;
import com.appkudos.view.R;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemClickListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;

public class GroupProfileActivity extends Activity implements ViewBinder {
	
	private Activity PARENTACTIVITY; 
	Spinner recToFriendSpinner;
	Spinner recToGroupSpinner;
	TextView appText;
	EditText commentEditText;
	Button postReviewBtn;
	UserController uc;
	GroupController gc;
	User user;
	User friend;
	TextView addRecButton;
	Group group;
	TextView groupname;
	TextView groupdesc;
	TextView rec;
	ListView groupRecList;
	ArrayList<Recommendation> groupRecs;
	TextView recommender;
	TextView datesent;
	TextView recText;
	TextView appName;
	String app_name;
	String display_option;
	
	
	String recid;
	String sender;
	String receiver;
	String msg;
	String isGroup;
	String isSent;
	String appid;

	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
    	PARENTACTIVITY = this;
        setContentView(R.layout.view_group_profile);
        
        // get info from previous screen
        Intent launchIntent = getIntent();
        Bundle extras = launchIntent.getExtras();
        uc = new UserController();
        user = uc.getCurrentUser(extras);
        gc = new GroupController();
        group = uc.getCurrentGroup(extras);
        friend = uc.getFriend(extras);
        display_option = extras.getString("display_opt");
        
        
        recid = extras.getString("recid");
    	sender = extras.getString("sender");
    	receiver = extras.getString("receiver");
    	msg = extras.getString("msg");
    	isGroup = extras.getString("isGroup");
    	isSent = extras.getString("isSent");
    	appid =  extras.getString("appid");
    	
        // if friend is in fact the user, then make friend null
        if(friend != null && friend.getUsername().compareTo(user.getUsername())==0){
        	friend = null;
        }

        
        if(display_option!= null){
	        if(display_option.equals(this.getString(R.string.view_rec))){ // display select app

	        	displayViewRec(sender,receiver,msg,appid,isSent);	    
	        }
	        
        }else{
	        // initialize fields
	        initWidgets();
        }
        
    }

    private boolean inGroup(Group curGroup){
    	List<Group> groups = uc.getGroupsOfUser(user.getUsername());
    	
    	return checkExistingGroup(groups, curGroup);
    }
    
	 // check if the user is already friends with matched user
	  private boolean checkExistingGroup(List<Group> existing_groups, Group matched){
		  boolean existed = false;
		  
		  for (int i=0; i<existing_groups.size();i++){
			  if(existing_groups.get(i).getGroupName().compareTo(matched.getGroupName()) == 0){
				  existed = true;
				  return existed;
			  }     
		  }
		  return existed;
	  }
    
    public void initWidgets() {
    	groupname = (TextView) findViewById(R.id.vg_groupname);
    	groupname.setText(group.getGroupName());
    	
    	groupdesc = (TextView) findViewById(R.id.vg_groupdesc);
    	groupdesc.setText(group.getGroupDesc());
    	
    	addRecButton = (TextView) findViewById(R.id.vg_rec_plus_button);
    	if(!inGroup(group)){
    		addRecButton.setVisibility(View.GONE);
    	}else{
	    	
	        addRecButton.setOnClickListener(new OnClickListener() {
	            @Override
	            public void onClick(View v) {     
	           	   //Toast.makeText(getApplicationContext(), "recommend button (from group) is clicked",Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(PARENTACTIVITY, AppKudos.class);
                    intent = uc.passCurrentUser(intent, user);
                    intent = uc.passCurrentGroup(intent,group);
                    intent.putExtra("tab", PARENTACTIVITY.getString(R.string.tab_user_app));
                    intent.putExtra("display_opt", "select_rec");
            		startActivity(intent);
	            }
	          }); 
    	}
    	
    	rec = (TextView)findViewById(R.id.vu_recommendation_textview);
    	rec.setVisibility(View.GONE);
    	
    	// get list view from layout
        groupRecList=(ListView)findViewById(R.id.vg_group_rec_list);
        
        
    	groupRecs = (ArrayList<Recommendation>) gc.getGroupRecs(group.getGroupID());
    	
    	//Toast.makeText(getApplicationContext(), groupRecs.size()+"",Toast.LENGTH_SHORT).show();
    	if (groupRecs.size() > 5){
    		groupRecList.setAdapter(new RecArrayAdapter(this, R.layout.two_line_list_item, groupRecs.subList(0, 5)));
    	}else{
    		groupRecList.setAdapter(new RecArrayAdapter(this, R.layout.two_line_list_item, groupRecs));
    	}
    	
    	groupRecList.setOnItemClickListener(new OnItemClickListener() {
    		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		        	
    			// When clicked, show a toast with the TextView text
	        	Recommendation item = (Recommendation) groupRecs.get(position);
//	        	Toast.makeText(getApplicationContext(), "Recommendation clicked",Toast.LENGTH_SHORT).show();
	               
//	        	displayViewRec(item.getSender(), item.getReceiver(), item.getMessage(), item.getAppid(), item.getDateSent());
            	Intent intent = new Intent(PARENTACTIVITY, AppKudos.class);
                intent = uc.passCurrentUser(intent, user);
                if(friend != null){
                	intent = uc.passFriend(intent, friend);	
                }
                intent = uc.passCurrentGroup(intent,group);
                intent.putExtra("display_opt", "view_rec");
                intent = uc.passRec(intent,item);
                intent.putExtra("tab", PARENTACTIVITY.getString(R.string.tab_group_profile));               
        		startActivity(intent); 

    		}
	    });
    }
	
    private void displayViewRec(String rec_sender, String rec_receiver, String rec_message, String app_id, String dateSent){
    	setContentView(R.layout.view_review);
    	String app_name = uc.getAppForUser(app_id).getAppName();
    	GroupController gc = new GroupController();
    	
    	DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM);
		Date d = new Date();
		try {
			d = df.parse(dateSent.substring(0, 10));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String date = df.format(d);
    	
    	recommender = (TextView) findViewById(R.id.vr_recommendation);
    	datesent = (TextView) findViewById(R.id.vr_datesent);
    	recText = (TextView) findViewById(R.id.vr_comment_text);
    	appName = (TextView) findViewById(R.id.vr_app_name);
    	    	
		recommender.setText(rec_sender + " recommended to " + group.getGroupName());
		datesent.setText("Date: " + date);
		recText.setText("Message: " + "\"" + rec_message + "\"" );
		appName.setText(app_name);
    }

	@Override
	public boolean setViewValue(View view, Object data,
			String textRepresentation) {
		// TODO Auto-generated method stub
		return false;
	}
   
}
